package com.white.commonlib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.DrawableRes;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.white.commonlib.R;
import com.white.commonlib.engine.CutDownner;

/**
 * Created by ytf on 2016/11/8.
 * 输入框的封装
 */
public class NormalInputBox extends RelativeLayout
{
    public static final int TEXT = 0;
    public static final int PASSWORD = 1;
    public static final int NUMBER = 2;

    /***输入方式*/
    private int inputType = TEXT;
    /***显示类型*/
    private int type;
    private int maxLength = -1;

    private String leftText;
    private int leftTextColor;
    private int leftTextViewWidth;
    private @DrawableRes int leftDrawable;

    private String hintText = "";
    private int hintTextColor;
    private int textColor;

    private int varicodeTextColor;
    private int contentLeftMargin;
    private int defaultColor = 0xDD4D4D4D;

    private int textSize = 15;
    private boolean hasFocus;
    private Paint mHightlightStrokePaint;
    private int highlightColor = 0xff1cb2f7;
    private int strokeColor = 0xffababab;
    private RectF mRectF;

    public NormalInputBox(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setWillNotDraw(false);
        setBackground(null);
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.NormalInputBox);
        inputType = typedArray.getInteger(R.styleable.NormalInputBox_inputType, 0);
        type = typedArray.getInteger(R.styleable.NormalInputBox_type, 0);
        hintText = typedArray.getString(R.styleable.NormalInputBox_hintText);
        maxLength = typedArray.getInteger(R.styleable.NormalInputBox_maxLength, -1);
        leftText = typedArray.getString(R.styleable.NormalInputBox_leftText);
        leftDrawable = typedArray.getResourceId(R.styleable.NormalInputBox_leftDrawable, 0);
        contentLeftMargin = (int) typedArray.getDimension(R.styleable.NormalInputBox_contentLeftMargin, 35);
        leftTextColor = typedArray.getColor(R.styleable.NormalInputBox_leftTextColor, defaultColor);
        leftTextViewWidth = (int) typedArray.getDimension(R.styleable.NormalInputBox_leftTextViewWidth, 180);
        varicodeTextColor = typedArray.getColor(R.styleable.NormalInputBox_variCodeColor, defaultColor);
        hintTextColor = typedArray.getColor(R.styleable.NormalInputBox_hintTextColor, defaultColor);
        textColor = typedArray.getColor(R.styleable.NormalInputBox_textColor, defaultColor);
        textSize = typedArray.getDimensionPixelSize(R.styleable.NormalInputBox_textSize, 15);
        typedArray.recycle();
        init();
    }

    private TextView leftTextView, varicodeTextView;
    private ImageView leftIcon;
    private ImageView deleteIcon;
    private EditText etContent;
    private RelativeLayout rt;

    private void init()
    {
        Context context = getContext();

        if(leftDrawable != 0)
        {
            createLeftIcon(context);
        }else
        {
            createLeftText(context);
        }

        if(type == 0)
        {
            createDeleteIcon(context);
        }else
        {
            createVaricodeText(context);
        }

        createContentTextView(context);

        initPaint();

        createAnim();
    }

    private TranslateAnimation anim;
    private void createAnim()
    {
        anim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, -0.02f,
                Animation.RELATIVE_TO_SELF,0.02f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f);
        anim.setDuration(55);
        anim.setRepeatCount(2);
        anim.setRepeatMode(Animation.REVERSE);
        anim.setInterpolator(new BounceInterpolator());
    }

    public void shake()
    {
        hasFocus = true;
        invalidate();
        if(anim != null)
        {
            clearAnimation();
            startAnimation(anim);
        }
    }

    /***
     * 从验证码输入模式切换至常规模式
     */
    public void changeTypeToNormal()
    {
        removeView(varicodeTextView);
        createDeleteIcon(getContext());
        bindChangeContentEvent();
        etContent.setText("");
    }

    private CutDownner cut;
    private void createVaricodeText(Context context)
    {
        varicodeTextView = new TextView(context);
        varicodeTextView.setId(R.id.NIB_RightId);
        LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        p.addRule(RelativeLayout.CENTER_VERTICAL);
        p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        varicodeTextView.setText("获取验证码");
        varicodeTextView.setPadding(50, 0, 50, 0);
        varicodeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize-5);
        varicodeTextView.setTextColor(varicodeTextColor);
        varicodeTextView.setLayoutParams(p);

        varicodeTextView.setGravity(Gravity.CENTER);
        addView(varicodeTextView);
        cut = new CutDownner(60);
        varicodeTextView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(l != null)
                {
                    l.onClick();
                }
            }
        });
        varicodeTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                varicodeTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                varicodeTextView.setBackground(createShape());
            }
        });
    }

    OnVaricodeClickListener l;
    public void setOnVaricodeClickListener(OnVaricodeClickListener l)
    {
        this.l = l;
    }
    public interface OnVaricodeClickListener
    {
        void onClick();
    }

    public void startCutdown()
    {
        cut.start(new CutDownner.Callback()
        {
            @Override
            public void onStart(int value)
            {
                varicodeTextView.setClickable(false);
                varicodeTextView.setText("重新获取"+value +"s");
            }

            @Override
            public void onCutdowing(int value)
            {
                varicodeTextView.setText("重新获取"+value +"s");
            }

            @Override
            public void onComplete()
            {
                varicodeTextView.setText("获取验证码");
                varicodeTextView.setClickable(true);
            }
        });
    }

    public void stopCutdown()
    {
        cut.recycle();
    }

    private void createLeftIcon(Context context)
    {
        if(leftDrawable != 0)
        {
            leftIcon = new ImageView(context);
            leftIcon.setId(R.id.NIB_LeftId);
            LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            p.addRule(RelativeLayout.CENTER_VERTICAL);
            p.leftMargin = 28;
            leftIcon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            leftIcon.setImageResource(leftDrawable);
            addView(leftIcon, p);
        }
    }

    private void createLeftText(Context context)
    {
        leftTextView = new TextView(context);
        LayoutParams p = new LayoutParams(leftTextViewWidth, LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.CENTER_VERTICAL);
        leftTextView.setId(R.id.NIB_LeftId);
        leftTextView.setText(leftText);
        leftTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        leftTextView.setTextColor(leftTextColor);
        leftTextView.setLayoutParams(p);
        addView(leftTextView);
    }

    @Override
    protected void onDetachedFromWindow()
    {
        if(cut != null)
        {
            cut.recycle();
        }
        super.onDetachedFromWindow();
    }

    private void createContentTextView(Context context)
    {
        etContent = new EditText(context);
        LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.CENTER_VERTICAL);
        p.addRule(RelativeLayout.RIGHT_OF, R.id.NIB_LeftId);
        p.addRule(RelativeLayout.LEFT_OF, R.id.NIB_RightId);
        p.leftMargin = contentLeftMargin;
        etContent.setBackground(null);
        etContent.setLayoutParams(p);
        //长度限制
        if (maxLength != -1)
        {
            etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        }
        etContent.setSingleLine();
        //输入类型设置
        changeInputType(inputType);
        etContent.setTextColor(textColor);
        etContent.setHintTextColor(hintTextColor);
        etContent.setHint(hintText);
        etContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

        if(type == 0)
        {
            bindChangeContentEvent();
        }
        etContent.setOnFocusChangeListener(new OnFocusChangeListener()
        {
            @Override
            public void onFocusChange(View v, boolean hasFocus)
            {
                if(hasFocus)
                {
                    NormalInputBox.this.hasFocus = true;
                    invalidate();
                    if(type == 0)
                    {
                        if(!TextUtils.isEmpty(etContent.getText()))
                        {
                            deleteIcon.setVisibility(VISIBLE);
                        }
                    }
                }else
                {
                    NormalInputBox.this.hasFocus = false;
                    invalidate();
                    if(type == 0)
                    {
                        deleteIcon.setVisibility(GONE);
                    }
                }
            }
        });
        addView(etContent);
    }

    /***
     * 修改输入类型
     * @param type
     */
    public void changeInputType(int type)
    {
        if (type == PASSWORD)
        {
            etContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else if (type == NUMBER)
        {
            etContent.setInputType(InputType.TYPE_CLASS_NUMBER);
        } else if(type == TEXT)
        {
            etContent.setInputType(InputType.TYPE_CLASS_TEXT);
        }
        etContent.setText("");
    }

    public void changeLeftIcon(@DrawableRes int d)
    {
        if(d != 0)
        {
            leftIcon.setImageResource(d);
        }
    }

    public void changeLeftText(CharSequence cs)
    {
        if(!TextUtils.isEmpty(cs))
        {
            leftTextView.setText(cs);
        }
    }

    public void changeMaxLength(int newLength)
    {
        if (newLength != -1)
        {
            maxLength = newLength;
            etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        }
    }

    public void changeHintText(CharSequence cs)
    {
        if(!TextUtils.isEmpty(cs))
        {
            etContent.setHint(cs);
        }
    }

    private void bindChangeContentEvent()
    {
        etContent.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                String str = charSequence.toString();
                if (!TextUtils.isEmpty(str))
                {
                    deleteIcon.setVisibility(View.VISIBLE);
                } else
                {
                    deleteIcon.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable)
            {
            }
        });
    }

    private void createDeleteIcon(Context context)
    {
        deleteIcon = new ImageView(context);
        deleteIcon.setId(R.id.NIB_RightId);
        LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.CENTER_VERTICAL);
        p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        p.rightMargin = 25;
        deleteIcon.setLayoutParams(p);
        deleteIcon.setImageResource(R.drawable.delete_grey);

        deleteIcon.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                etContent.setText("");
                deleteIcon.setVisibility(View.GONE);
            }
        });
        deleteIcon.setVisibility(GONE);
        addView(deleteIcon);
    }

    private void initPaint()
    {
        mHightlightStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mHightlightStrokePaint.setStyle(Paint.Style.STROKE);
        mHightlightStrokePaint.setStrokeWidth(1);
    }

    public void setContentDisEditable(boolean yn)
    {
        etContent.setFocusable(yn);
        etContent.setFocusableInTouchMode(yn);
        etContent.setClickable(yn);
    }

    public void setText(CharSequence ct)
    {
        etContent.setText(ct);
    }
//
    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        super.dispatchDraw(canvas);
        if(hasFocus)
        {
            mHightlightStrokePaint.setColor(highlightColor);
            canvas.drawRoundRect(mRectF, height/10, height/10, mHightlightStrokePaint);
        }else
        {
            mHightlightStrokePaint.setColor(strokeColor);
            canvas.drawRoundRect(mRectF, height/10, height/10, mHightlightStrokePaint);
        }
    }

    public String getContent()
    {
        CharSequence cs = etContent.getText();
        return TextUtils.isEmpty(cs) ? "" : etContent.getText().toString();
    }

    private int width;
    private int height;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
        mRectF = new RectF(0.5f,0.5f,width-0.5f,height-0.5f);
    }

    private Drawable createShape()
    {
        float radius = height * 1.0f / 10;
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setColor(Color.parseColor("#FFE9E9E9"));
        drawable.mutate();
        drawable.setCornerRadii(new float[]{
                0,     0,
                radius,    radius,
                radius,      radius,
                0,  0});

//        drawable.setStroke(2, color);
        return drawable;
    }
}
